<?php

namespace paymch\controllers;

use Yii;
use yii\web\Controller;
use paymch\models\TradeForm;

/**
 * TradeController 用于交易处理
 * 
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class TestController extends Controller {

    /**
     * 当前控制器禁用CSRF校验
     * @internal
     */
    public $enableCsrfValidation = false;

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => \yii\filters\VerbFilter::className(),
                'actions' => [
                    'index' => ['get'],
                    'close' => ['get'],
                    'refund' => ['get'],
                ],
            ],
        ];
    }

    /**
     * actionClose
     * 
     * @view close.php
     * @return mixed
     */
    public function actionWechatDeRefund() {
        $test = [
            'out_refund_no' => '501171209127594551',
            'out_trade_no' => '501171209897504130',
            'refund_account' => 'REFUND_SOURCE_UNSETTLED_FUNDS',
            'refund_fee' => '10',
            'refund_id' => '50000304942017120902591839814',
            'refund_recv_accout' => '支付用户零钱',
            'refund_request_source' => 'API',
            'refund_status' => 'SUCCESS',
            'settlement_refund_fee' => '10',
            'settlement_total_fee' => '100',
            'success_time' => '2017-12-09 03:32:42',
            'total_fee' => '100',
            'transaction_id' => '4200000021201712090325234387',
        ];
        $query = \common\models\trade\TradeOrder::find()->alias('t')->joinWith('trade trade')
        ->where(['trade.trade_no' => '501171209127594551'])
        ->where(['t.paymode' => \common\models\trade\TradeOrder::PAYMODE_WECHAT]);


        $query->one();

        \common\helpers\Debug::sql($query);

        return \yii\helpers\VarDumper::export($test);

        $encryptData = 'If0qReyBm/JHsec5Oz+xw3CLSDDmHdhUa6yt+HzPpHV4MYxPYgvxkMzyDFREusBICGmx43XDumKdZRwJ3UjaBFgpLsmlYR2VvhpA/bT9UhLI0jDQsQwk2dph79aGtk3nQO/1a/l+dvVmkSoq7wkYVs1e1crePqtZrVsOo5V1aj2O0ZjNXacTnax7DhqF0kBVUfJDJqte/DGu+1sEGJTABybCDCsD9FE5om9YzNFF34iwPBwVNEBtePD7j5g0/meHlxSuz74M5qRlm945pAFJNzlM5nyQmQPu6Q9sC3KDET5n4kUK5wMe4fvcu/BH9Crx/rFJoLJU+ZtYjpGbWw4ajQJvXOd/DaG8dIdNZIlKkv1jUIFLo++gEVheGs/SDFtE7HU8d+7Cjak+rwCkl/RJz6lOu4zh/oque0MnWCLhdqMKpPtnULesqmg9jRYe3o1ImIccDnyCmhVQCl6iovqZndvjEk3GlVM+5jyK0qeFaNKN1wyX6eU/KGKVuO53Y1TUd3RpGgGNL0Fd89vjTcJRXDgMlDzM1au1wUeo7tYXr5FQ5o+8CY43Ofp+s9COIkVdz5LDEuG8dqP3zh18F2PF/qRPZKlHbupaxx1eBwfet++3PoZwI13d1Nrlg/RfuVPsfsD7X+vItTqDtCHlNB6/sxXpcnI/wB1PMznqrfkrB4KXXa1To++pdUxzAVI6RiUzfgbiy/xpuZ+eZM8JvndoVGauNwVWeC2nFneR4F9p5mNpt++IvEn9xpht1y0aoQ547sZ3LilPebF04O/PWLLYKBOrtuRBWMb5ysulYXq9CkeHOlSZLV4+sCxJNn9JWIchTxiuTvRw/xayR76apOpQdfxzMyIqJkK0CECJYvLvV2u+7JhF95PaTSm4RQtdUv+mNRi1LalOmH8HM72HnxkIc6Dtvz2RyljbDsgEh254QYNBxDKFz+UfBD9iA2K+dlg6sIa4cKEOsU3/rHVcsTjaps4iLhh+eVC74S/d1dI1hFvR5WBdO7uwa8CgE6WNk9H/bUBVNYdo6FhbGTYP2dZ7VzneXTH2OoxUKQDbTpmtQr0=';
        $request = \paymch\models\WechatRefund::decryptData($encryptData, Yii::$app->params['wechat']['partner_key']);
        //$data = \paymch\models\RefundHandler::trade(54, $msg);

        if ($request == false) {
            $requestData = '加密信息解密失败！';
        } else {
            $requestData = \paymch\components\wechat\HttpDataFormatter::fromXml($request);
        }

        return \yii\helpers\VarDumper::export($requestData);

        $host = Yii::$app->request->hostInfo;

        $client = new \common\components\paymch\MchClient();
        $client->appId = '201710139118';
        $client->rsaPrivateKeyFilePath = Yii::getAlias('@common') . '/data/keys/emchpay/rsa_private_key.pem';

        $client->gatewayUrl = $host . '/trade/refund';

        $client->signType = 'RSA2';
        $client->postCharset = 'utf-8';
        $client->apiVersion = '1.0';
        $params = [
            'bizno' => 'SHOP001', //退款单号
            'original_trade_no' => '301171125549713857', //原交易号
            'user_id' => 1,
            'paymode' => 'alipay', //支付时现金使用的支付方式
            'total_amount' => 0.1, //总退款金额（元）
            'point_amount' => 0.1, //总退款中积分部分的金额（元）
            'body' => '退款描述',
        ];
        $data = $client->render($params);

        return \yii\helpers\VarDumper::export($data);
    }

    /**
     * actionRefund
     * Description
     *
     * @view template.php
     * @return mixed
     */
    public function actionRefund() {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $aop = new \paymch\components\alipay\aop\AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = Yii::$app->params['alipay']['appid'];
        $aop->rsaPrivateKey = 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQD0O4X7hUgrmT7J+4rCV1Rb/86l+dNIzua4HRQbZm+pwDEmgoKEwz6UUp2TMR1tKZuxQtDZqZH495SoqsAkar8vOMri4MrFS0lmHH6iyYIMIGSzPZEqMJRffzCutXoCJUWD++fYUyn2cRn+esic1+/Fh6uzo1B5nznF6ThQ75ubzX+S0p8WnHUeBlBwQ+nOe4krjVDu2a1aoCc9c8YgTKZtDlAqlSljqbG3kPZNEASoxov2Wzh7xYpuQNDXgOAmnwNDoWkdqiNI+SWOc05tBJi5WVnGtqPkzbdQKsP13lkw4Eu9W+D14RdFVjdD2jmM+9z+b0BsI0aZ0+7AcKyt2x43AgMBAAECggEAEQEv8/I0syxpTcDgyWUxL3KhHbdGObSGJd2Ib9vy/FuwUGEX20yIx+T0qbHqvZX/DBl91xnSWwZJ6HBzDlYMV6pZnfBOzevPAXgMbSMgld2PhVdNCyX0vq1pY1CpXQrhSy431zz7F/iJ+cjsvNbgD93BW7GMQduPNzNkw2XbbL6ASJuiresgdkGZIZtLoSKaIzojGJELBeSPWME1ODWdxkxd05og6U3I/FQH0ElTIVZ4j0BptWJsfKGtT4gn6gZ+cfpdtI+jKWtCZcg8g4OCRFtcMDRAUAsEdCsLo+Mw7O9uITySnctptXeffhGMmbCVKIIX16qy/8xexdfjjUS0WQKBgQD6QMRDpAMjRIqlQY5yNIQQIJlHEGAQ+S4d6vur/N747do0ucUolNZprHtLUmmtfVb5jgPXbIrr4ueuS8YhbTBIuHN+dSQ/WHAJoRLDx7wGI3VTvUc6onfYL+uuA8jYadO5s4ITcVuB0GJWdGOA7HgmAUlOJkYIm5OIVgP5EjECdQKBgQD511zGEbgZY1Nrt8095ybryK4A2l8nLyTheJafsoBcbqUmC8XR0zfqLQa8hY3bJNaHCL4bVZNFHMJVBvZp/3ubJ8ZPtGXQlKut2ZfXzUiydbVQn25fT/M2v8bPiiI/vx5aAoSXBUcObC6Qiy77xPiy8b7AooRH5UPKUu+uU1UwewKBgQC88XN9gnKgCRsJBIMRNRdUudggcHuntQsdqZIU25pZpfOvBWeXaTCtnn2EdBe31j95scCywI/u42V7EljoWfEvppwEqVsRvKryijuJt979X34xGGKUIaCMiDnQK6lTxCsINUELfvXRAE2O6tdJusBIKYZ4S6tqylPMhuz++74nFQKBgQDSNZ6sVFpGmiilODeqvuMjfWzR8OogiO0J/DEXWtPfcYTolv0xRvsDwDCry98IJF2Prg5t5zmK6+CiM8J+euQgLn4Pr+P+dChilPLKMsHYzWrp08rEzPsA9KitFDcu1XoPF5FBk8IuY11mZoT4dskdnoL1h4evCjpYcCGT1i+WIwKBgQDroCMSy28ElypZQvp8ZagSqJHGy5i/KdklRmbfWT99IEtx8G9E/ptUpM98bECXIStpu+w1qhM/CMkvdBeW+E5PtVYIZmod8Xdy11XBiS2zIBjJHmZXR6Y1INjK02Yn69xu8WlD3o0PX9I7OrZw97MwXBuEMSSqOdmQ3ZUwWjWgpQ==';
        $aop->alipayrsaPublicKey = Yii::$app->params['alipay']['public'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new \paymch\components\alipay\aop\request\AlipayTradeRefundRequest();

        $data = [
            "out_trade_no" => "2017102110290016",
            "trade_no" => "2017102121001004180227754995",
            "refund_amount" => 0.01,
            "refund_reason" => "正常测试部分退款",
            "out_request_no" => "HZ01RF004",
        ];
        $jsonstring = \yii\helpers\Json::encode($data);
        $request->setBizContent($jsonstring);
        return $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            return "成功";
        } else {
            return "失败";
        }
    }

    /**
     * actionCreate
     * Description
     *
     * @view create.php
     * @return mixed
     */
    public function actionQuery() {

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $aop = new \paymch\components\alipay\aop\AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = Yii::$app->params['alipay']['appid'];
        $aop->rsaPrivateKey = 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQD0O4X7hUgrmT7J+4rCV1Rb/86l+dNIzua4HRQbZm+pwDEmgoKEwz6UUp2TMR1tKZuxQtDZqZH495SoqsAkar8vOMri4MrFS0lmHH6iyYIMIGSzPZEqMJRffzCutXoCJUWD++fYUyn2cRn+esic1+/Fh6uzo1B5nznF6ThQ75ubzX+S0p8WnHUeBlBwQ+nOe4krjVDu2a1aoCc9c8YgTKZtDlAqlSljqbG3kPZNEASoxov2Wzh7xYpuQNDXgOAmnwNDoWkdqiNI+SWOc05tBJi5WVnGtqPkzbdQKsP13lkw4Eu9W+D14RdFVjdD2jmM+9z+b0BsI0aZ0+7AcKyt2x43AgMBAAECggEAEQEv8/I0syxpTcDgyWUxL3KhHbdGObSGJd2Ib9vy/FuwUGEX20yIx+T0qbHqvZX/DBl91xnSWwZJ6HBzDlYMV6pZnfBOzevPAXgMbSMgld2PhVdNCyX0vq1pY1C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Q==';
        $aop->alipayrsaPublicKey = Yii::$app->params['alipay']['public'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new \paymch\components\alipay\aop\request\AlipayTradeQueryRequest();
        $data = [
            "out_trade_no" => "2017102110290016",
            "trade_no" => "2017102121001004180227754995",
        ];
        $jsonstring = \yii\helpers\Json::encode($data);
        $request->setBizContent($jsonstring);
        return $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            echo "成功";
        } else {
            echo "失败";
        }
    }

}
